const md5 = require("md5");
const {
    login,
    register,
    find,
    detail,
    update,
    follow,
    followers,
    followingTopics,
} = require("../model/user");
const { generateToken } = require("../utils/jwt");
const { isObjectId } = require("../utils/validate");
const { getTokenData } = require("../utils/jwt");
const { getselects } = require("../utils/getselects");
// 用户登录
const Login = async (ctx) => {
    const { username, password } = ctx.request.body;
    if (username && password) {
        const user = await login(username, md5(password));
        if (user) {
            const token = generateToken({ _id: user._id, username });
            ctx.set("Authorization", token);
            ctx.state.user = user;
            ctx.body = {
                code: 200,
                msg: "登录成功",
                token,
                data: user,
            };
        } else {
            ctx.status = 401;
            ctx.body = {
                code: 401,
                msg: "用户名或密码错误",
                data: null,
            };
        }
    } else {
        ctx.status = 400;
        ctx.body = {
            code: 400,
            msg: "用户名或密码不能为空",
            data: null,
        };
    }
};

// 用户注册
const Register = async (ctx) => {
    const { username, password } = ctx.request.body;
    if (username && password) {
        const isExist = await find({ username });
        if (isExist) {
            ctx.status = 401;
            return (ctx.body = {
                code: 401,
                msg: "用户名已存在",
                data: null,
            });
        }
        const user = await register(username, md5(password));
        if (user) {
            ctx.body = {
                code: 200,
                msg: "注册成功",
            };
        } else {
            ctx.status = 401;
            ctx.body = {
                code: 401,
                msg: "用户名已存在",
                data: null,
            };
        }
    } else {
        ctx.status = 400;
        ctx.body = {
            code: 400,
            msg: "用户名或密码不能为空",
            data: null,
        };
    }
};

// 获取用户信息
const Detail = async (ctx) => {
    const id = ctx.params.id;
    const selects = getselects(ctx.query.fields);
    if (!isObjectId(id)) {
        ctx.status = 400;
        return (ctx.body = {
            code: 400,
            msg: "用户ID不合法",
            data: null,
        });
    }
    const user = await detail(id, selects);
    if (!user) {
        ctx.status = 401;
        return (ctx.body = {
            code: 401,
            msg: "用户不存在",
            data: null,
        });
    }
    ctx.body = {
        code: 200,
        msg: "获取用户信息成功",
        data: user,
    };
};

// 更新用户信息

const Update = async (ctx) => {
    const id = ctx.params.id;
    const data = ctx.request.body;
    if (!isObjectId(id)) {
        ctx.status = 400;
        return (ctx.body = {
            code: 400,
            msg: "用户ID不合法",
            data: null,
        });
    }
    const token =
        (ctx.headers.authorization &&
            ctx.headers.authorization.split(" ")[1]) ||
        "";
    const { _id } = getTokenData(token);
    if (_id !== id) {
        ctx.status = 401;
        return (ctx.body = {
            code: 403,
            msg: "无权限修改用户信息",
            data: null,
        });
    }
    const user = await update(id, data);
    if (user) {
        ctx.body = {
            code: 200,
            msg: "更新用户信息成功",
            data: user,
        };
    } else {
        ctx.status = 401;
        ctx.body = {
            code: 401,
            msg: "更新用户信息失败",
            data: null,
        };
    }
};

// 获取用户关注列表
const Follow = async (ctx) => {
    const id = ctx.params.id;
    if (!isObjectId(id)) {
        ctx.status = 400;
        return (ctx.body = {
            code: 400,
            msg: "用户ID不合法",
            data: null,
        });
    }
    const user = await follow(id);
    if (user) {
        ctx.body = {
            code: 200,
            msg: "获取用户关注列表成功",
            data: user.following,
        };
    } else {
        ctx.status = 401;
        ctx.body = {
            code: 401,
            msg: "获取用户关注列表失败",
            data: null,
        };
    }
};

// 关注
const FollowUser = async (ctx) => {
    const token =
        (ctx.headers.authorization &&
            ctx.headers.authorization.split(" ")[1]) ||
        "";
    const { _id } = getTokenData(token);
    const id = ctx.params.id;
    if (!isObjectId(id)) {
        ctx.status = 400;
        return (ctx.body = {
            code: 400,
            msg: "用户ID不合法",
            data: null,
        });
    }
    if (id == _id) {
        ctx.status = 401;
        return (ctx.body = {
            code: 401,
            msg: "不能关注自己",
            data: null,
        });
    }
    const myself = await find({ _id }, "+following");
    if (myself.following.map((id) => id.toString()).includes(id)) {
        ctx.status = 401;
        return (ctx.body = {
            code: 401,
            msg: "不能重复关注",
            data: null,
        });
    }
    myself.following.push(id);
    myself.save();
    ctx.body = {
        code: 200,
        msg: "关注成功",
        data: null,
    };
};

// 取消关注
const UnFollowUser = async (ctx) => {
    const token =
        (ctx.headers.authorization &&
            ctx.headers.authorization.split(" ")[1]) ||
        "";
    const { _id } = getTokenData(token);
    const id = ctx.params.id;
    if (!isObjectId(id)) {
        ctx.status = 400;
        return (ctx.body = {
            code: 400,
            msg: "用户ID不合法",
            data: null,
        });
    }
    if (id == _id) {
        ctx.status = 401;
        return (ctx.body = {
            code: 401,
            msg: "不能关注自己",
            data: null,
        });
    }
    const myself = await find({ _id }, "+following");
    const index = myself.following
        .map((f) => f.toString())
        .findIndex((f) => f == id);
    if (index < 0) {
        ctx.status = 401;
        return (ctx.body = {
            code: 401,
            msg: "关注列表中不存在该用户",
            data: null,
        });
    }
    myself.following.splice(index, 1);
    myself.save();
    ctx.body = {
        code: 200,
        msg: "取消关注成功",
        data: null,
    };
};

// 粉丝列表
const Followers = async (ctx) => {
    const id = ctx.params.id;
    if (!isObjectId(id)) {
        ctx.status = 400;
        return (ctx.body = {
            code: 400,
            msg: "用户ID不合法",
            data: null,
        });
    }
    const user = await followers(id);
    if (user) {
        ctx.body = {
            code: 200,
            msg: "获取粉丝列表成功",
            data: user,
        };
    }
};

// 关注话题
const FollowTopic = async (ctx) => {
    const token =
        (ctx.headers.authorization &&
            ctx.headers.authorization.split(" ")[1]) ||
        "";
    const { _id } = getTokenData(token);
    const id = ctx.params.id;
    if (!isObjectId(id)) {
        ctx.status = 400;
        return (ctx.body = {
            code: 400,
            msg: "话题ID不合法",
            data: null,
        });
    }
    const myself = await find({ _id }, "+followingTopics");
    if (myself.followingTopics.map((id) => id.toString()).includes(id)) {
        ctx.status = 401;
        return (ctx.body = {
            code: 401,
            msg: "不能重复关注",
            data: null,
        });
    }
    myself.followingTopics.push(id);
    myself.save();
    ctx.body = {
        code: 200,
        msg: "关注成功",
        data: null,
    };
};
// 取消关注话题
const UnFollowTopic = async (ctx) => {
    const token =
        (ctx.headers.authorization &&
            ctx.headers.authorization.split(" ")[1]) ||
        "";
    const { _id } = getTokenData(token);
    const id = ctx.params.id;
    if (!isObjectId(id)) {
        ctx.status = 400;
        return (ctx.body = {
            code: 400,
            msg: "话题ID不合法",
            data: null,
        });
    }
    const myself = await find({ _id }, "+followingTopics");
    const index = myself.followingTopics
        .map((f) => f.toString())
        .findIndex((f) => f == id);
    if (index < 0) {
        ctx.status = 401;
        return (ctx.body = {
            code: 401,
            msg: "关注列表中不存在该话题",
            data: null,
        });
    }
    myself.followingTopics.splice(index, 1);
    myself.save();
    ctx.body = {
        code: 200,
        msg: "取消关注成功",
        data: null,
    };
};

// 用户关注话题列表
const FollowingTopics = async (ctx) => {
    const id = ctx.params.id;
    if (!isObjectId(id)) {
        ctx.status = 400;
        return (ctx.body = {
            code: 400,
            msg: "用户ID不合法",
            data: null,
        });
    }
    const user = await followingTopics(id);
    if (user) {
        ctx.body = {
            code: 200,
            msg: "获取用户关注话题列表成功",
            data: user.followingTopics,
        };
    } else {
        ctx.status = 401;
        ctx.body = {
            code: 401,
            msg: "获取用户关注列表失败",
            data: null,
        };
    }
};

module.exports = {
    Login,
    Register,
    Detail,
    Update,
    Follow,
    FollowUser,
    UnFollowUser,
    Followers,
    FollowTopic,
    UnFollowTopic,
    FollowingTopics,
};
